from permissions.serializers import MenuModelSerializer, MenuSerializer


class MenuTree:

    @staticmethod
    def make_router(queryset, parent_id=None):
        router = []
        new_queryset = [q for q in queryset if q.parent_id == parent_id]
        for q in new_queryset:
            serializer = MenuModelSerializer(q)
            data = serializer.data
            children = MenuTree.make_router(queryset, q.id)
            if children:
                data['children'] = children
            # if router.count(data) > 0:
            #     continue
            router.append(data)
        return router

    @staticmethod
    def make_menu_tree(queryset, parent_id=None, serializer_class=MenuSerializer, menu_id_list=None):
        menu_tree = []
        new_queryset = [q for q in queryset if q.parent_id == parent_id]
        for q in new_queryset:
            serializer = serializer_class(q)
            data = serializer.data
            if menu_id_list:
                data['disabled'] = data.get('id') not in menu_id_list
            children = MenuTree.make_menu_tree(queryset, q.id, serializer_class=serializer_class, menu_id_list=menu_id_list)
            if children:
                data['children'] = children
            menu_tree.append(data)
        return menu_tree


class DepartmentTree:

    @staticmethod
    def make_department_tree(data, parent_id):
        department_list = []
        new_data = list(filter(lambda d: d.get('parent_id') == parent_id, data))
        for department in new_data:
            children = DepartmentTree.make_department_tree(data, department.get('id'))
            if children:
                department['children'] = children
            department_list.append(department)
        return department_list
